package com.kg.sdk.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.network.NetworkConfigData;
import com.common.network.NetworkResponse;
import com.common.network.RequestListener;
import com.kg.sdk.network.KPPostRequest;
import com.kg.sdk.util.CommonTimer;
import com.kg.sdk.util.CommonUtil;
import com.kg.sdk.util.Helper;
import com.kg.sdk.util.KPNetworkData;
import com.kg.sdk.view.TCMLoadInputLayout;

import org.json.JSONException;
import org.json.JSONObject;

public class KPResetPwdActivity extends KPCommonActivity implements View.OnClickListener,CommonTimer.OnTimeChangedListener {
    public TCMLoadInputLayout liAccount;
    public TCMLoadInputLayout liPassword;
    public TCMLoadInputLayout liEmailCode;
    public TCMLoadInputLayout liEmail;
    public View line1;
    public final static int CHECKOUT_ACCOUNT  = 100;
    public final static int CHECKOUT_EMAIL  = 101;
    public final static int RESET_PASSWORD  = 102;
    public Button btnPwdReset;
    public int resetStyle = CHECKOUT_ACCOUNT;
    private int step = 1;
    private String accountNoNull;
    private String passwordNoNull;
    private String againPasswordNoNull;
    private String emailNoNull;
    private String codeNoNull;
    private String getPhoneCode;
    private int codeId = 4761;
    private String reset_pwd_code;
    private ImageView imLogo;
    private CommonTimer mTimer;
    private final int MAX_TIME = 60;
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        int layoutId = Helper.getLayoutResId(this,"act_reset_pwd_layout");
        setContentView(layoutId);
        /*
        accountNoNull = getResources().getString(R.string.accountNoNull);
        passwordNoNull = getResources().getString(R.string.passwordNoNull);
        againPasswordNoNull = getResources().getString(R.string.againPasswordNoNull);
        emailNoNull = getResources().getString(R.string.emailNoNull);
        getPhoneCode = getResources().getString(R.string.getPhoneCode);
        codeNoNull = getResources().getString(R.string.codeNoNull);*/

        accountNoNull = getResources().getString(Helper.getStringResId(this,"accountNoNull"));
        passwordNoNull = getResources().getString(Helper.getStringResId(this,"passwordNoNull"));
        againPasswordNoNull = getResources().getString(Helper.getStringResId(this,"againPasswordNoNull"));
        emailNoNull = getResources().getString(Helper.getStringResId(this,"emailNoNull"));
        getPhoneCode = getResources().getString(Helper.getStringResId(this,"getPhoneCode"));
        codeNoNull = getResources().getString(Helper.getStringResId(this,"codeNoNull"));

        liAccount = (TCMLoadInputLayout)findViewById( Helper.getIdResId(this,"liAccount"));
        liPassword = (TCMLoadInputLayout)findViewById(Helper.getIdResId(this,"liPassword"));
        liEmailCode = (TCMLoadInputLayout)findViewById(Helper.getIdResId(this,"liEmailCode"));
        liEmail = (TCMLoadInputLayout)findViewById(Helper.getIdResId(this,"liEmail"));
        imLogo = (ImageView) findViewById(Helper.getIdResId(this,"imLogo"));
        line1 = findViewById(Helper.getIdResId(this,"line1"));
        imLogo.setVisibility(View.GONE);
       // liAccount.setEditText("kp111111");
      //  liEmail.setEditText("374479716@qq.com");
     //   liEmailCode.setEditText("6bAJp");
        liPassword.setPasswordShow();
        liPassword.setVisibility(View.GONE);
        liEmailCode.setVisibility(View.GONE);
        liEmail.setVisibility(View.GONE);
        line1.setVisibility(View.GONE);
        btnPwdReset = (Button)findViewById(Helper.getIdResId(this,"btnPwdReset"));
        btnPwdReset.setOnClickListener(this);
        liEmailCode.setBtnRightClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                getEmailCode();
            }
        });

        TextView tvTopLeft = (TextView)findViewById(Helper.getIdResId(this,"tvTopLeft"));
        TextView tvTopRight = (TextView)findViewById(  Helper.getIdResId(this,"tvTopRight"));

        tvTopLeft.setText(getResources().getString(Helper.getStringResId(this,"resetPassword")));
        tvTopRight.setText( getResources().getString(Helper.getStringResId(this,"kpCancel")));
        tvTopLeft.setTextColor(0xff001A33);
        tvTopRight.setTextColor(0xff515A6E);
        tvTopRight.setOnClickListener(this);
        mTimer = new CommonTimer();
        mTimer.setOnTimeChange(this);

        liAccount.setInputStyle(TCMLoadInputLayout.TEXT);
        liPassword.setInputStyle(TCMLoadInputLayout.PASSOWRD);
        liEmail.setInputStyle(TCMLoadInputLayout.TEXT);
        liEmailCode.setInputStyle(TCMLoadInputLayout.CHECK);

        liAccount.setHit("inputAccount");
        liPassword.setHit("inputPassword");
        liEmail.setHit("inputEmail");
        liEmailCode.setHit("inputEmailCode");

        liAccount.setImgDrawable("kp_account_user");
        liPassword.setImgDrawable("kp_account_password");
        liEmail.setImgDrawable("kp_account_message");
        liEmailCode.setImgDrawable("kp_account_check");
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if(id ==  Helper.getIdResId(this,"tvTopRight")){
            finish();
            return;
        }
        if(resetStyle == CHECKOUT_ACCOUNT){
            checkoutAccount();
        }else if(resetStyle == CHECKOUT_EMAIL){
            checkEmail(codeId);
        }else if(RESET_PASSWORD == resetStyle){
            resetPassword(reset_pwd_code);
        }
    }

    private void checkoutAccount(){
        String account = liAccount.getInputText();
        if(account.length() == 0){
            CommonUtil.showToast(this,accountNoNull);
            return;
        }
        RequestListener listener = new RequestListener() {
            @Override
            public void onSuccess(NetworkResponse result) {
                int code = result.getInt(KPNetworkData.ERROR_CODE);
                String data = result.getString(NetworkConfigData.DATA_KEY);
                Log.e("data","checkoutAccount error is "+data+" code is "+code);
                if(code == KPNetworkData.SUCCESS){
                    CommonUtil.getXSID(result);
                    resetStyle = CHECKOUT_EMAIL;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mWaitingDialog.closeDialog();
                            liAccount.setVisibility(View.GONE);
                            line1.setVisibility(View.VISIBLE);
                            liEmailCode.setVisibility(View.VISIBLE);
                            liEmail.setVisibility(View.VISIBLE);
                        }
                    });
                }else{
                    final String errorMsg = result.getString(KPNetworkData.MSG_KEY);
                    Log.e("data","checkoutAccount error1111 is "+errorMsg);
                    showError(errorMsg);
                }

            }

            @Override
            public void onError(NetworkResponse error) {
                String data = error.getString(NetworkConfigData.MESSAGE_KEY);
                Log.e("data","checkoutAccount error is "+data);
            }
        };
        mWaitingDialog.showDialog();
        String url = KPNetworkData.RESET_PASSWORD;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(NetworkConfigData.USER_KEY,account);
            jsonObject.put(KPNetworkData.STEP_KEY,1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("data"," jsonData is "+jsonObject.toString());
        KPPostRequest postRequest = new KPPostRequest(this,url,jsonObject.toString(),listener);
        postRequest.startAsync();
    }

    private void checkEmail(int codeId){
        String email = liEmail.getInputText();
        String emailCode = liEmailCode.getInputText();
        if(email.length() == 0){
            CommonUtil.showToast(this,emailNoNull);
            return;
        }
        if(emailCode.length() == 0){
            CommonUtil.showToast(this,codeNoNull);
            return;
        }
        RequestListener listener = new RequestListener() {
            @Override
            public void onSuccess(NetworkResponse result) {
                int code = result.getInt(KPNetworkData.ERROR_CODE);
                if(code == KPNetworkData.SUCCESS){
                    String data = result.getString(NetworkConfigData.DATA_KEY);
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        reset_pwd_code = jsonObject.getString(KPNetworkData.reset_pwd_code);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    resetStyle = RESET_PASSWORD;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            stopTime();
                            mWaitingDialog.closeDialog();
                            liAccount.setVisibility(View.GONE);
                            liEmailCode.setVisibility(View.GONE);
                            liEmail.setVisibility(View.GONE);
                            line1.setVisibility(View.GONE);
                            liPassword.setVisibility(View.VISIBLE);

                            btnPwdReset.setText(getResources().getString(Helper.getStringResId(KPResetPwdActivity.this,"pwdReset")));
                        }
                    });
                }else{
                    final String errorMsg = result.getString(KPNetworkData.MSG_KEY);
                    Log.e("data","email error1111 is "+errorMsg);
                    showError(errorMsg);
                }

            }

            @Override
            public void onError(NetworkResponse error) {
                String data = error.getString(NetworkConfigData.MESSAGE_KEY);
                Log.e("data","email code   onerror message is "+data);
                showError(data);
            }
        };
        String url = KPNetworkData.RESET_PASSWORD;
        String account = liAccount.getInputText();

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(NetworkConfigData.USER_KEY,account);
            jsonObject.put(NetworkConfigData.EMAIL_KEY,email);
            jsonObject.put(KPNetworkData.CODE_ID_KEY,codeId);
            jsonObject.put(KPNetworkData.STEP_KEY,2);
            jsonObject.put(KPNetworkData.CODE_KEY,emailCode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mWaitingDialog.showDialog();
        KPPostRequest postRequest = new KPPostRequest(this,url,jsonObject.toString(),listener);
        postRequest.startAsync();
    }

    private void getEmailCode(){
        startTime();
        RequestListener listener = new RequestListener() {
            @Override
            public void onSuccess(NetworkResponse result) {
                int code = result.getInt(KPNetworkData.ERROR_CODE);
                String data = result.getString(NetworkConfigData.DATA_KEY);
                Log.e("data"," email data is "+data);
                if(code == KPNetworkData.SUCCESS){
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        codeId = jsonObject.getInt(KPNetworkData.CODE_ID_KEY);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }else{
                    final String errorMsg = result.getString(KPNetworkData.MSG_KEY);
                    Log.e("data","email code error1111 is "+errorMsg);
                    showError(errorMsg);
                }

            }

            @Override
            public void onError(NetworkResponse error) {
                String data = error.getString(NetworkConfigData.MESSAGE_KEY);
                Log.e("data","email code   onerror message is "+data);
                showError(data);
            }
        };
        String url = KPNetworkData.SEND_EMAIL_CODE;
        String account = liAccount.getInputText();
        String email = liEmail.getInputText();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(NetworkConfigData.USER_KEY,account);
            jsonObject.put(NetworkConfigData.EMAIL_KEY,email);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        KPPostRequest postRequest = new KPPostRequest(this,url,jsonObject.toString(),listener);
        postRequest.startAsync();
    }
    private void resetPassword(String reset_pwd_code){
        String password = liPassword.getInputText();
        if(password.length() == 0){
            CommonUtil.showToast(this,passwordNoNull);
            return;
        }
        RequestListener listener = new RequestListener() {
            @Override
            public void onSuccess(NetworkResponse result) {
                int code = result.getInt(KPNetworkData.ERROR_CODE);
                if(code == KPNetworkData.SUCCESS){
                    String data = result.getString(NetworkConfigData.DATA_KEY);
                    Log.e("data","resetPassword success data is "+data);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mWaitingDialog.closeDialog();
                            showError(getResources().getString(Helper.getStringResId(KPResetPwdActivity.this,"kpResetPasswordSuccess")));
                            setResult(KPNetworkData.RESET_PASSWORD_SUCCESS);
                            finish();
                        }
                    });
                }else{
                    final String errorMsg = result.getString(KPNetworkData.MSG_KEY);
                    Log.e("data","resetPassword error1111 is "+errorMsg);
                    showError(errorMsg);
                }

            }

            @Override
            public void onError(NetworkResponse error) {
                String data = error.getString(NetworkConfigData.MESSAGE_KEY);
                Log.e("data","checkoutAccount error is "+data);
                showError(data);
            }
        };
        String url = KPNetworkData.RESET_PASSWORD;
        String account = liAccount.getInputText();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(NetworkConfigData.USER_KEY,account);
            jsonObject.put(KPNetworkData.STEP_KEY,3);
            jsonObject.put(KPNetworkData.reset_pwd_code,reset_pwd_code);
            jsonObject.put(KPNetworkData.newpwd,password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        KPPostRequest postRequest = new KPPostRequest(this,url,jsonObject.toString(),listener);
        postRequest.startAsync();
    }

    private void showError(final String error){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWaitingDialog.closeDialog();
                CommonUtil.showToast(KPResetPwdActivity.this,error);
            }
        });
    }

    public void startTime(){
        liEmailCode.setBtnRightEnable(false);
        mTimer.stopTime();
        mTimer.startTime();
    }

    public void stopTime(){
        mTimer.stopTime();
    }

    @Override
    public void timeChange(int time) {
        StringBuilder builder = new StringBuilder();
        builder.append((MAX_TIME-time)+"s");
        liEmailCode.setBtnRightText(builder.toString());
        if(time == MAX_TIME){
            setGetPhoneCodeOver();
        }
    }

    private void setGetPhoneCodeOver(){
        mTimer.stopTime();
        liEmailCode.setBtnRightEnable(true);
        liEmailCode.setBtnRightText(getPhoneCode);
    }

    public void onDestroy(){
        super.onDestroy();
        stopTime();
    }

}
